package cn.zt.middleware.dynamic.thread.pool.sdk.trigger.job;

import cn.zt.middleware.dynamic.thread.pool.sdk.domain.IDynamicThreadPoolService;
import cn.zt.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.zt.middleware.dynamic.thread.pool.sdk.registry.IRegistry;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * @author: zhangtao
 * @description: 线程池数据上报定时任务
 * @date: 2024-08-09 14:51
 */

public class ThreadPoolDataReportJob {

    private final Logger logger = LoggerFactory.getLogger(ThreadPoolDataReportJob.class);


    private final IDynamicThreadPoolService dynamicThreadPoolService;

    private final IRegistry registry;

    public ThreadPoolDataReportJob(IDynamicThreadPoolService dynamicThreadPoolService, IRegistry registry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = registry;
    }

    /**
     * 定时任务：上报线程池信息
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void executeReportThreadPool() {
        try {
            // 1. 获取线程池信息
            List<ThreadPoolConfigEntity> threadPoolConfigEntities = dynamicThreadPoolService.queryThreadPoolConfigs();
            // 2. 上传到配置中心
            registry.reportThreadPoolConfigList(threadPoolConfigEntities);
            logger.info("动态线程池，上传线程池信息：{}", JSON.toJSONString(threadPoolConfigEntities));
            for (ThreadPoolConfigEntity threadPoolConfigEntity : threadPoolConfigEntities) {
                registry.reportThreadPoolConfig(threadPoolConfigEntity);
                logger.info("动态线程池，上传线程池配置：{}", JSON.toJSONString(threadPoolConfigEntity));
            }
        } catch (Exception ex) {
            logger.error("动态线程池，上传线程池信息异常：{}", ex.getMessage());
        }

    }
}
